package com.config;

import org.apache.logging.log4j.web.Log4jServletContextListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.util.IntrospectorCleanupListener;

import javax.servlet.*;
import java.util.Enumeration;


public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * @return Spring 应用上下文配置类
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{RootConfig.class};
    }

    /**
     * @return Servlet Web 上下文配置类
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebConfig.class};
    }

    /**
     * @return 匹配的 URL 模式
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }


    @Override
    protected void registerContextLoaderListener(ServletContext servletContext) {
        super.registerContextLoaderListener(servletContext);
        servletContext.addListener(RequestContextListener.class);
    }

    @Override
    protected Filter[] getServletFilters() {
        return super.getServletFilters();
    }

    @Override
    protected void registerDispatcherServlet(ServletContext servletContext) {
        super.registerDispatcherServlet(servletContext);
        servletContext.addListener(new IntrospectorCleanupListener());
        servletContext.addListener(new Log4jServletContextListener());
        servletContext.setInitParameter("log4jConfiguration", "classpath:log4j2.xml");
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);

        servletContext.addFilter("delegatingFilterProxy", DelegatingFilterProxy.class)
                .addMappingForUrlPatterns(null, false, "/*");
    }

}